<template>
  <div class="paper-template-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1>试卷模板管理</h1>
          <p>管理试卷模板，支持智能组卷和手工组卷</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            创建模板
          </el-button>
          <el-button @click="handleBatchGenerate">
            <el-icon><Document /></el-icon>
            批量生成试卷
          </el-button>
        </div>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" :inline="true">
          <el-form-item label="模板名称">
            <el-input
              v-model="filterForm.search"
              placeholder="请输入模板名称"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="模板类型">
            <el-select v-model="filterForm.paper_type" placeholder="请选择" clearable>
              <el-option label="正式考试" value="formal" />
              <el-option label="模拟考试" value="mock" />
              <el-option label="练习试卷" value="practice" />
              <el-option label="竞赛试卷" value="competition" />
            </el-select>
          </el-form-item>
          <el-form-item label="组卷方式">
            <el-select v-model="filterForm.generation_method" placeholder="请选择" clearable>
              <el-option label="随机组卷" value="random" />
              <el-option label="智能组卷" value="intelligent" />
              <el-option label="手工组卷" value="manual" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="filterForm.date_range"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in templateStats" :key="stat.key">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                <el-icon><component :is="stat.icon" /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 模板列表 -->
    <div class="template-list">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>模板列表</span>
            <div class="header-controls">
              <el-button-group>
                <el-button
                  :type="viewMode === 'grid' ? 'primary' : 'default'"
                  @click="viewMode = 'grid'"
                >
                  <el-icon><Grid /></el-icon>
                </el-button>
                <el-button
                  :type="viewMode === 'list' ? 'primary' : 'default'"
                  @click="viewMode = 'list'"
                >
                  <el-icon><List /></el-icon>
                </el-button>
              </el-button-group>
            </div>
          </div>
        </template>

        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" class="grid-view">
          <el-row :gutter="20">
            <el-col :span="8" v-for="template in filteredTemplates" :key="template.id">
              <el-card class="template-card" shadow="hover" @click="viewTemplate(template)">
                <div class="template-header">
                  <div class="template-title">{{ template.title }}</div>
                  <el-tag :type="getTypeColor(template.paper_type)" size="small">
                    {{ getTypeLabel(template.paper_type) }}
                  </el-tag>
                </div>

                <div class="template-info">
                  <div class="info-row">
                    <span class="label">总分：</span>
                    <span class="value">{{ template.total_score }}分</span>
                  </div>
                  <div class="info-row">
                    <span class="label">时长：</span>
                    <span class="value">{{ template.duration }}分钟</span>
                  </div>
                  <div class="info-row">
                    <span class="label">题目数：</span>
                    <span class="value">{{ template.total_questions }}题</span>
                  </div>
                  <div class="info-row">
                    <span class="label">组卷方式：</span>
                    <el-tag size="small">
                      {{ getMethodLabel(template.generation_method) }}
                    </el-tag>
                  </div>
                </div>

                <div class="template-description">
                  {{ template.description || '暂无描述' }}
                </div>

                <div class="template-actions">
                  <el-button size="small" @click.stop="editTemplate(template)">编辑</el-button>
                  <el-button size="small" type="success" @click.stop="generatePaper(template)">
                    生成试卷
                  </el-button>
                  <el-dropdown @command="(cmd) => handleCommand(cmd, template)" @click.stop>
                    <el-button size="small">
                      更多<el-icon><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="copy">复制模板</el-dropdown-item>
                        <el-dropdown-item command="export">导出模板</el-dropdown-item>
                        <el-dropdown-item command="statistics">统计分析</el-dropdown-item>
                        <el-dropdown-item command="delete" divided>删除模板</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>

                <div class="template-footer">
                  <div class="usage-info">
                    <span>使用次数：{{ template.usage_count }}</span>
                    <span>创建时间：{{ formatDate(template.created_at) }}</span>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 列表视图 -->
        <div v-else class="list-view">
          <el-table :data="filteredTemplates" @row-click="viewTemplate">
            <el-table-column prop="title" label="模板名称" min-width="200">
              <template #default="{ row }">
                <div class="template-name">
                  <el-link type="primary" @click.stop="viewTemplate(row)">
                    {{ row.title }}
                  </el-link>
                  <el-tag :type="getTypeColor(row.paper_type)" size="small">
                    {{ getTypeLabel(row.paper_type) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="试卷信息" width="300">
              <template #default="{ row }">
                <div class="paper-info">
                  <div>总分：{{ row.total_score }}分</div>
                  <div>时长：{{ row.duration }}分钟</div>
                  <div>题目：{{ row.total_questions }}题</div>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="generation_method" label="组卷方式" width="120">
              <template #default="{ row }">
                <el-tag size="small">
                  {{ getMethodLabel(row.generation_method) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="difficulty_distribution" label="难度分布" width="200">
              <template #default="{ row }">
                <div class="difficulty-chart">
                  <el-tooltip content="简单" placement="top">
                    <div class="difficulty-bar easy" :style="{ width: getDifficultyPercent(row, 'easy') }"></div>
                  </el-tooltip>
                  <el-tooltip content="中等" placement="top">
                    <div class="difficulty-bar medium" :style="{ width: getDifficultyPercent(row, 'medium') }"></div>
                  </el-tooltip>
                  <el-tooltip content="困难" placement="top">
                    <div class="difficulty-bar hard" :style="{ width: getDifficultyPercent(row, 'hard') }"></div>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="usage_count" label="使用次数" width="100" sortable />

            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click.stop="editTemplate(row)">编辑</el-button>
                <el-button size="small" type="success" @click.stop="generatePaper(row)">
                  生成试卷
                </el-button>
                <el-dropdown @command="(cmd) => handleCommand(cmd, row)" @click.stop>
                  <el-button size="small">
                    更多<el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="copy">复制模板</el-dropdown-item>
                      <el-dropdown-item command="export">导出模板</el-dropdown-item>
                      <el-dropdown-item command="statistics">统计分析</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除模板</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current_page"
            v-model:page-size="pagination.page_size"
            :page-sizes="[12, 24, 48, 96]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 创建/编辑模板对话框 -->
    <CreateTemplateDialog
      v-model="showCreateDialog"
      :template="editingTemplate"
      @success="handleCreateSuccess"
    />

    <!-- 生成试卷对话框 -->
    <GeneratePaperDialog
      v-model="showGenerateDialog"
      :template="selectedTemplate"
      @success="handleGenerateSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Document, Grid, List, ArrowDown,
  Collection, DocumentCopy, TrendCharts, SetUp
} from '@element-plus/icons-vue'
import { examPaperApi } from '@/api/examPaper'
import CreateTemplateDialog from './components/CreateTemplateDialog.vue'
import GeneratePaperDialog from './components/GeneratePaperDialog.vue'
import { format } from 'date-fns'

const router = useRouter()

// 响应式数据
const viewMode = ref<'grid' | 'list'>('grid')
const showCreateDialog = ref(false)
const showGenerateDialog = ref(false)
const editingTemplate = ref(null)
const selectedTemplate = ref(null)
const templates = ref([])
const loading = ref(false)

// 筛选表单
const filterForm = reactive({
  search: '',
  paper_type: '',
  generation_method: '',
  date_range: []
})

// 分页
const pagination = reactive({
  current_page: 1,
  page_size: 12,
  total: 0
})

// 统计数据
const templateStats = computed(() => [
  {
    key: 'total',
    label: '总模板数',
    value: pagination.total,
    color: '#409EFF',
    icon: 'Document'
  },
  {
    key: 'intelligent',
    label: '智能组卷',
    value: templates.value.filter(t => t.generation_method === 'intelligent').length,
    color: '#67C23A',
    icon: 'SetUp'
  },
  {
    key: 'usage',
    label: '平均使用率',
    value: templates.value.length > 0
      ? Math.round(templates.value.reduce((sum, t) => sum + t.usage_count, 0) / templates.value.length)
      : 0,
    color: '#E6A23C',
    icon: 'TrendCharts'
  },
  {
    key: 'active',
    label: '活跃模板',
    value: templates.value.filter(t => t.is_active).length,
    color: '#F56C6C',
    icon: 'Collection'
  }
])

// 计算属性
const filteredTemplates = computed(() => {
  let result = templates.value

  if (filterForm.search) {
    result = result.filter(template =>
      template.title.toLowerCase().includes(filterForm.search.toLowerCase()) ||
      template.description?.toLowerCase().includes(filterForm.search.toLowerCase())
    )
  }

  if (filterForm.paper_type) {
    result = result.filter(template => template.paper_type === filterForm.paper_type)
  }

  if (filterForm.generation_method) {
    result = result.filter(template => template.generation_method === filterForm.generation_method)
  }

  if (filterForm.date_range && filterForm.date_range.length === 2) {
    const [startDate, endDate] = filterForm.date_range
    result = result.filter(template => {
      const templateDate = template.created_at.split(' ')[0]
      return templateDate >= startDate && templateDate <= endDate
    })
  }

  return result
})

// 方法
const loadTemplates = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current_page,
      page_size: pagination.page_size
    }
    const response = await examPaperApi.getTemplates(params)
    templates.value = response.data.results
    pagination.total = response.data.count
  } catch (error) {
    console.error('Failed to load templates:', error)
    ElMessage.error('加载模板列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current_page = 1
  loadTemplates()
}

const handleReset = () => {
  Object.assign(filterForm, {
    search: '',
    paper_type: '',
    generation_method: '',
    date_range: []
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.page_size = size
  loadTemplates()
}

const handleCurrentChange = (page: number) => {
  pagination.current_page = page
  loadTemplates()
}

const viewTemplate = (template: any) => {
  router.push(`/exam-paper/templates/${template.id}`)
}

const editTemplate = (template: any) => {
  editingTemplate.value = template
  showCreateDialog.value = true
}

const generatePaper = (template: any) => {
  selectedTemplate.value = template
  showGenerateDialog.value = true
}

const handleBatchGenerate = () => {
  if (filteredTemplates.value.length === 0) {
    ElMessage.warning('请先选择模板')
    return
  }
  showGenerateDialog.value = true
}

const handleCommand = async (command: string, template: any) => {
  switch (command) {
    case 'copy':
      await copyTemplate(template)
      break
    case 'export':
      await exportTemplate(template)
      break
    case 'statistics':
      viewStatistics(template)
      break
    case 'delete':
      await deleteTemplate(template)
      break
  }
}

const copyTemplate = async (template: any) => {
  try {
    const response = await examPaperApi.copyTemplate(template.id)
    ElMessage.success('模板复制成功')
    loadTemplates()
  } catch (error) {
    console.error('Failed to copy template:', error)
    ElMessage.error('模板复制失败')
  }
}

const exportTemplate = async (template: any) => {
  try {
    const response = await examPaperApi.exportTemplate(template.id)
    // 下载文件
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${template.title}.json`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('模板导出成功')
  } catch (error) {
    console.error('Failed to export template:', error)
    ElMessage.error('模板导出失败')
  }
}

const viewStatistics = (template: any) => {
  router.push(`/exam-paper/templates/${template.id}/statistics`)
}

const deleteTemplate = async (template: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除模板"${template.title}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await examPaperApi.deleteTemplate(template.id)
    ElMessage.success('模板删除成功')
    loadTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete template:', error)
      ElMessage.error('模板删除失败')
    }
  }
}

const handleCreateSuccess = () => {
  showCreateDialog.value = false
  editingTemplate.value = null
  loadTemplates()
}

const handleGenerateSuccess = () => {
  showGenerateDialog.value = false
  selectedTemplate.value = null
  ElMessage.success('试卷生成成功')
}

// 辅助方法
const getTypeColor = (type: string) => {
  const colors = {
    formal: 'primary',
    mock: 'success',
    practice: 'warning',
    competition: 'danger'
  }
  return colors[type] || 'info'
}

const getTypeLabel = (type: string) => {
  const labels = {
    formal: '正式考试',
    mock: '模拟考试',
    practice: '练习试卷',
    competition: '竞赛试卷'
  }
  return labels[type] || type
}

const getMethodLabel = (method: string) => {
  const labels = {
    random: '随机组卷',
    intelligent: '智能组卷',
    manual: '手工组卷'
  }
  return labels[method] || method
}

const getDifficultyPercent = (template: any, difficulty: string) => {
  const distribution = template.difficulty_distribution || {}
  const total = Object.values(distribution).reduce((sum: number, count: number) => sum + count, 0)
  if (total === 0) return '0%'
  const percent = ((distribution[difficulty] || 0) / total * 100).toFixed(1)
  return `${percent}%`
}

const formatDate = (dateString: string) => {
  return format(new Date(dateString), 'yyyy-MM-dd HH:mm')
}

// 生命周期
onMounted(() => {
  loadTemplates()
})
</script>

<style scoped>
.paper-template-list {
  padding: 24px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 64px);
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  color: var(--el-text-color-primary);
}

.title-section p {
  margin: 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.filter-section {
  margin-bottom: 24px;
}

.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  height: 100%;
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
  font-size: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.template-list {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.grid-view {
  min-height: 400px;
}

.template-card {
  height: 320px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.template-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.template-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  line-height: 1.4;
  flex: 1;
  margin-right: 8px;
}

.template-info {
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
  font-size: 13px;
}

.info-row .label {
  color: var(--el-text-color-regular);
}

.info-row .value {
  color: var(--el-text-color-primary);
  font-weight: 500;
}

.template-description {
  font-size: 13px;
  color: var(--el-text-color-regular);
  line-height: 1.4;
  margin-bottom: 16px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.template-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.template-footer {
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 12px;
}

.usage-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.list-view {
  min-height: 400px;
}

.template-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.paper-info {
  font-size: 13px;
  line-height: 1.5;
}

.difficulty-chart {
  display: flex;
  height: 6px;
  border-radius: 3px;
  overflow: hidden;
  background-color: var(--el-fill-color-lighter);
}

.difficulty-bar {
  height: 100%;
  transition: width 0.3s ease;
}

.difficulty-bar.easy {
  background-color: #67C23A;
}

.difficulty-bar.medium {
  background-color: #E6A23C;
}

.difficulty-bar.hard {
  background-color: #F56C6C;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .paper-template-list {
    padding: 16px;
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
    display: flex;
    gap: 12px;
  }

  .stats-section .el-col {
    margin-bottom: 16px;
  }

  .grid-view .el-col {
    span: 24;
  }

  .template-card {
    height: auto;
    min-height: 300px;
  }
}
</style>